<?php

namespace Database\Seeders;

use App\Models\Virtual\Virtual;
use App\Models\Virtual\VirtualWord;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class VirtualDataSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $virtuals = DB::connection('rjmysql')->table('virtuals')->get()->toArray();
        $virtuals = json_decode(json_encode($virtuals), true);

        foreach ($virtuals as $virtual) {
            if (DB::table('categorys')->where('id', $virtual['unit_id'])->exists()) {
                Virtual::query()->updateOrCreate(
                    ['id' => $virtual['id']],
                    $virtual
                );
                $this->save_virtual_word($virtual['id']);
            }
        }

        $this->command->info('情境学习数据填充完成！');
    }

    protected function save_virtual_word(int $virtual_id): void
    {
        $virtual_words = DB::connection('rjmysql')->table('virtual_words')
            ->where('virtual_id', $virtual_id)->get()->toArray();
        $virtual_words = json_decode(json_encode($virtual_words), true);

        foreach ($virtual_words as $virtual_word) {
            VirtualWord::query()->updateOrCreate(
                ['id' => $virtual_word['id']],
                $virtual_word
            );
        }
    }
}
